package com.kma.ncpractice2013.servlets;

import com.kma.ncpractice2013.auth.Crypto;
import com.kma.ncpractice2013.dao.UserDAO;
import com.kma.ncpractice2013.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: Viktor
 * Date: 11/17/13
 */

public class PasswordServlet extends HttpServlet
{
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String oldPass = request.getParameter("oldpass");
		String newPass = request.getParameter("newpass");
		String username = (String) request.getSession().getAttribute("username");
		if(Crypto.getAccessLevel(username, oldPass) != Crypto.INVALID_CREDENTIALS)
		{
			UserDAO userDAO = new UserDAO();
			User user = userDAO.getByLogin(username);
			user.setPassword(Crypto.getHash(user.getSalt(), newPass, "SHA-256"));
			userDAO.update(user);
			response.getWriter().print("Password changed");

		}
		else response.getWriter().print("Invalid password");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

	}
}
